﻿package  com.mattlohkamp.src.as3	{
	/**
	 * ...
	 * @author matt lohkamp
	 */
	public class LoopedList	{
		public var items:Array;
		public function get length():int{return items.length;}
		public var loop:Boolean;
		public var current:*;
		public var old:*;
		public function LoopedList(_items:* = null, _loop:Boolean=true)	{
			this.loop = _loop;
			this.init();
			this.add(_items);
		}
		public function init():LoopedList	{
			items = new Array();
			return this;
		}
		public function add(_items:*, ignoreArray:Boolean = false):Array	{
			if(_items is Array && ignoreArray != true){	// you're adding a bunch of items, remove the first item and add just it, and then keep calling this recursively.
				this.add(_items.shift());
				if(_items.length > 0){this.add(_items)}
			}else if(_items!=null){	// if it's a single item, just add it
				items.push(_items);
					// and if this is the first/only item, default to it being the 'current'
				if(items.length == 1){current = _items;}
			}
			return items;
		}
		public function next():*	{
			return change(1);
		}
		public function previous():*	{
			return change(-1);
		}
		public function change(delta:int):*	{
			var newIndex:int = items.indexOf(current) + delta;
				// adjust the newIndex so its within bounds, either at the end or looped over
			if(this.loop != true){
				if(newIndex >= items.length){	// hit the max
					newIndex = items.length - 1;
				}else if(newIndex < 0){	// hit the min
					newIndex = 0;
				}
			}else{	// this ELSE case is the glorious part of this glorified Array, admittedly, since it allows you to jump to an index that doesn't exist (below 0 or above length) and have it 'wrap' to the appropriate value
					// if it's positive, this'll wrap around to the min
				newIndex %= items.length;
					// and if it's negative, this'll wrap back up to the max
				while(newIndex < 0){newIndex += items.length}
			}
			return show(items[newIndex]);
		}
		public function show(target:*):*	{
			old = current;
			current = target;
			return current;
		}
	}
}